package khleuven.mondzorg.app;

import khleuven.mondzorg.R;
import khleuven.mondzorg.domain.DentalCareApp;
import khleuven.mondzorg.domain.DestinationGroup;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
 
public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener{
	
	public static final String KEY_PREF_TARGET = "pref_targetgroup";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        addPreferencesFromResource(R.xml.settings);    
    }
    

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals(KEY_PREF_TARGET)) {
            Preference targetpref = findPreference(key);
            String chosenValue = sharedPreferences.getString(key, "");
            targetpref.setSummary(chosenValue);            

    		String[] targets = getResources().getStringArray(R.array.Level); 
    		for(int i = 0; i < targets.length; i++){
    			if(chosenValue.equals(targets[i])){
    				DentalCareApp.getInstance().setDestination(DestinationGroup.values()[i]);
    			}
    		}
    	}
    }
    
    @Override
	public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
        
        Preference targetpref = findPreference(KEY_PREF_TARGET);     
        SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
        String chosenValue = sharedPreferences.getString(KEY_PREF_TARGET, "");
        targetpref.setSummary(chosenValue);  
    }

    @Override
	public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }
}
